package ah.hbmtools.comment;

import java.io.File;
import java.io.FilenameFilter;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import file.FileCopy;
/**
 * 把类似&#191;&#170;&#202;&#188;BEGIN&#202;&#177;&#188;&#228;转成 "开始BEGIN时间"
 * @author user
 *
 */
public class Convert {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		String basePath = "E:\\workspace\\peixun\\src\\com\\kingee\\wsfm\\bean";
		String[] dirs = new String[]{"\\kb"};
		for (String dir : dirs) {
			String[] files = new File(basePath + dir).list(new FilenameFilter() {
				public boolean accept(File dir, String name) {
					if (name.endsWith(".hbm.xml")) {
						return true;
					}
					return false;
				}
			});
			
			if (files!=null) {
				for (String file : files) {
					convertFile(basePath + dir + "\\" + file);
				}
			}
			
		}
		
	}
	
	public static void convertFile(String fileName) throws UnsupportedEncodingException {
		Pattern pattern = Pattern.compile("<comment>\\s*(.*)\\s*</comment>");
		String content = FileCopy.readFileStr(fileName);
		
		StringBuffer newContent = new StringBuffer();
		
		Matcher matcher = pattern.matcher(content);
		
		
		while (matcher.find()) {
			
			String comment = matcher.group(0);
			
			matcher.appendReplacement(newContent, convertComment(comment));
		}
		matcher.appendTail(newContent);
		FileCopy.writeFile(fileName, newContent.toString());
	}
	
	
	public static String convertComment(String comment) throws UnsupportedEncodingException {
		Pattern pattern = Pattern.compile("(&#(\\d+);)(&#((\\d+));)");//括号?
		Matcher matcher = pattern.matcher(comment);
		
		StringBuffer sb = new StringBuffer();
		boolean flag = matcher.find();
		if (!flag) {
			return comment;
		}
		
		byte[] word = new byte[2];
		while (flag) {
			/*System.out.println(matcher.groupCount());
			for (int i=0; i<matcher.groupCount(); i++) {
				System.out.println(matcher.group(i));
			}*/
			
			try {
				
				word[0] = (byte)(Integer.parseInt(matcher.group(2)) - 256);
				word[1] = (byte)(Integer.parseInt(matcher.group(4)) - 256);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
			matcher.appendReplacement(sb, new String(word, "GBK"));
			flag = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString().replaceAll("\\s+", "");
	}
}
